﻿using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using 纸片人.AttributeUsageFloder;
using 纸片人.InfoDataFolder;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace 纸片人.GpuPage
{
    [LastModified("2022-5-15", "create DistortionPage.xaml")]
    [PageType("gpu", "扭曲效果")]
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class DistortionPage : Page
    {
        CanvasRenderTarget renderTarget;
        CanvasRenderTarget tempTarget;
        float angle = (float)Math.PI * 2f / 360f;
        Vector2 pos;
        float radius = 30;

        //是否进入来了
        bool isEntry;


        float effectWidth = 0;
        float effectHeight = 0;
        float previewWidth = 0;
        float previewHeight = 0;

        float offsetX, offsetY, scale, width, height;

        //是否按下
        bool isPressed;

        public DistortionPage()
        {
            this.InitializeComponent();
            Init();
        }
        LayerBitmapData bitmapData = new LayerBitmapData();

        private void Init()
        {
            selectPicture.Click += async (s, e) =>
            {
                await bitmapData.SelectOneBitmapAsync(canvas.Device);
                if (bitmapData.oneBitmap != null)
                {
                    CalcuationPosition();
                    renderTarget = new CanvasRenderTarget(canvas, bitmapData.oneBitmap.Size);
                    using (var ds = renderTarget.CreateDrawingSession())
                    {
                        ds.DrawImage(bitmapData.oneBitmap);
                    }
                    tempTarget = new CanvasRenderTarget(canvas, bitmapData.oneBitmap.Size);
                }
            };

            Action DrawDistortion = () =>
            {
                if (!isPressed)
                    return;
                using (var ds = tempTarget.CreateDrawingSession())
                {
                    ds.Clear(Colors.Transparent);
                    ds.DrawImage(renderTarget);
                }

                PixelShaderEffect effect = new PixelShaderEffect(bitmapData.oneShaderCode)
                {
                    Source1 = tempTarget,
                    Properties = {
                        ["angle"] = angle ,
                        ["position"]=(pos-new Vector2(offsetX,offsetY))/scale,
                        ["radius"]=radius,
                    }
                };

                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.DrawImage(effect);
                }

            };

            canvas.CreateResources += (s, e) =>
            {
                e.TrackAsyncAction(bitmapData.LoadOneShadeCodeAsync(Shaders.ShaderType.Distortion).AsAsyncAction());
            };
            canvas.Draw += (s, e) =>
            {
                Function.DrawGridGraphics(e.DrawingSession);

                if (renderTarget != null)
                {


                    var previewTran = Function.CalcutateImageCenteredTransform(previewWidth, previewHeight, bitmapData.oneWidth, bitmapData.oneHeight);
                    previewTran.Source = bitmapData.oneBitmap;
                    e.DrawingSession.DrawImage(previewTran, 0, effectHeight);

                    var effectTran = Function.CalcutateImageCenteredTransform(effectWidth, effectHeight, bitmapData.oneWidth, bitmapData.oneHeight);
                    effectTran.Source = renderTarget;
                    e.DrawingSession.DrawImage(effectTran);

                    //是否进入范围
                    if (isEntry && (pos.X >= offsetX && pos.X <= offsetX + width && pos.Y >= offsetY && pos.Y <= offsetY + height))
                    {
                        DrawDistortion();

                        e.DrawingSession.DrawCircle(pos, radius * scale, Colors.Black, 4f);
                        e.DrawingSession.DrawCircle(pos, radius * scale, Colors.White, 2f);
                    }
                }
            };

            canvas.PointerEntered += (s, e) =>
            {
                isEntry = true;
            };

            canvas.PointerExited += (s, e) =>
            {
                isEntry = false;
            };

            canvas.PointerMoved += (s, e) =>
            {
                pos = e.GetCurrentPoint(canvas).Position.ToVector2();
                CalcuationPosition();
            };

            canvas.PointerPressed += (s, e) =>
            {
                isPressed = true;
                canvas.Invalidate();
            };

            canvas.PointerReleased += (s, e) =>
            {
                isPressed = false;
                canvas.Invalidate();

            };

            radiusSlider.ValueChanged += (s, e) =>
            {
                radius = (float)radiusSlider.Value * Math.Max(bitmapData.oneWidth, bitmapData.oneHeight) / 2f;

            };

            canvas.SizeChanged += (s, e) =>
            {
                CalcuationPosition();
            };

            reset.Click += (s, e) =>
           {
               if (bitmapData.oneBitmap != null && renderTarget != null)
               {
                   using (var ds = renderTarget.CreateDrawingSession())
                   {
                       ds.Clear(Colors.Transparent);
                       ds.DrawImage(bitmapData.oneBitmap);
                   }
               }
           };
        }


        void CalcuationPosition()
        {
            if (bitmapData.oneBitmap == null)
                return;

            radius = (float)radiusSlider.Value * Math.Max(bitmapData.oneWidth, bitmapData.oneHeight) / 2f;

            var element = canvas;
            effectWidth = (float)element.ActualWidth;
            effectHeight = (float)element.ActualHeight * 0.7f;
            previewWidth = effectWidth;
            previewHeight = (float)element.ActualHeight * 0.3f;

            var mat = Function.CalcutateImageCenteredMat(effectWidth, effectHeight, bitmapData.oneWidth, bitmapData.oneHeight);
            scale = mat.M11;
            offsetX = mat.M31;
            offsetY = mat.M32;
            width = scale * bitmapData.oneWidth;
            height = scale * bitmapData.oneHeight;
        }

    }
}
